import requests
import re
import base64
import io
from fontTools.ttLib import TTFont
from html import unescape


def decode58(text):
    """自定义字体转换"""
    base64_str = re.findall(
        r'data:application/font-ttf;charset=utf-8;base64,(.*)\'\) format\(\'truetype\'\)}', text)
    bin_data = base64.b64decode(base64_str[0])
    fonts = TTFont(io.BytesIO(bin_data))
    bestcmap = fonts.getBestCmap()
    newmap = {}
    for key in bestcmap.keys():
        # print(key)
        # print(re.findall(r'(\d+)', bestcmap[key]))
        value = int(re.findall(r'(\d+)', bestcmap[key])[0])-1
        key = hex(key)
        newmap[key] = value

        # print('==========', newmap)
    resp_ = text
    for key, value in newmap.items():
        key_ = key.replace('0x', '&#x') + ';'
        if key_ in resp_:
            resp_ = resp_.replace(key_, str(value))
    return resp_


data = {
    'PGTID': '0d3090a7-0000-537e-0f78-afa8cade3647',
    'ClickID': 2
}
url = "http://su.58.com/chuzu/"

res = requests.get(url, params=data)

html = res.content.decode('utf-8')
html = decode58(html)
html = unescape(html)  # HTML编码转换

# 匹配每条租房信息
pat = r'<li logr=.*\s*.*>([\s\S]*?)</li>'
dlist = re.findall(pat, html)
# 每条租房信息取出需要的内容
pat2 = r'<img[\s\S]*?src="(.*?)"[\s\S]*<h2>\s*<a[\s\S]*?>\s*(.*?)\s*</a>[\s\S]*</h2>\s*<p class="room strongbox">(.*?)</p>[\s\S]*?<div class="money">\s*<b class="strongbox">(.*?)</b>(.*?)</div>[\s\S]*</div>'

# print(len(dlist))

for v in dlist:
    dlist2 = re.findall(pat2, v)
    for d in dlist2:
        print("标题："+d[1] + "   "+"图片："+d[0] + "   " +
              "户型："+d[2]+"   "+"价格："+d[3]+" "+d[4])
